package club.calong.sanniu.controller;

import club.calong.sanniu.http.request.UserRequest;
import club.calong.sanniu.http.response.Response;
import club.calong.sanniu.pojo.User;
import club.calong.sanniu.pojo.WxUser;
import club.calong.sanniu.service.InfoService;
import club.calong.sanniu.service.PlateService;
import club.calong.sanniu.service.SectionService;
import club.calong.sanniu.service.UserService;
import club.calong.sanniu.util.CacheUtils;
import club.calong.sanniu.util.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.util.LinkedMultiValueMap;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    UserService service;

    InfoService infoService;

    PlateService plateService;

    SectionService sectionService;

    @Autowired
    public UserController(UserService service,
                          InfoService infoService,
                          PlateService plateService,
                          SectionService sectionService) {
        this.service = service;
        this.infoService = infoService;
        this.plateService = plateService;
        this.sectionService = sectionService;
    }


    @GetMapping("/wxlogin")
    public Response wxlogin(String code ){
        String appId = "wx8a42b7e70e266e71";
        String secret = "6b0673b945a7f16feacefc016c0ba4a4";
        String grantType = "authorization_code";
        Map<String, String> queries = new HashMap<>();
        queries.put("appid",appId);
        queries.put("secret",secret);
        queries.put("code",code);
        queries.put("grant_type",grantType);

        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + appId
                + "&secret=" + secret
                + "&code=" + code
                + "&grant_type=" + grantType;
        String token_str =  HttpUtils.get2(accessTokenUrl,queries);
        System.out.println("weixin return is :"+token_str);
        if(token_str == null)
            return new Response(Response.SUCCESS, "data error");
        JSONObject result = JSONObject.parseObject(token_str);
        String openid , access_token;
        try{
            openid = result.get("openid").toString();
            access_token = result.get("access_token").toString();
            if(access_token == null){
                return new Response(Response.FAILURE, "code已过期",null);
            }
        }catch (Exception e){
            return new Response(Response.FAILURE, "code已过期",null);
        }


        //查询用户信息
        User checkuser = service.checkexits(openid);
        if(checkuser  != null){
            return new Response(Response.SUCCESS, checkuser);
        } else {
            // 用户不存在 获取用户基本信息，
            String baseinfoUrl = "https://api.weixin.qq.com/sns/userinfo?"
                    + "access_token=" + access_token
                    + "&openid=" + openid;
            String baseinfo_str = HttpUtils.get2(baseinfoUrl,queries);
            System.out.println("weixin return is :"+baseinfo_str);
            JSONObject baseinfo_json = JSONObject.parseObject(baseinfo_str);
            WxUser user1= WxUser.ConvertToWXUser(baseinfo_json);
            return new Response(Response.SUCCESS, user1);
        }
    }


    @PostMapping("/wxRegist")
    public Response wxRegist(@RequestBody JSONObject req ){
        User user = new User();
        user.openid = req.getString("openid");
        user.setAvatar(req.getString("headimgurl"));
        user.setPhone(req.getString("phone"));
        user.setName(req.getString("nickname"));
        user.setActivated(false);
        service.wxregist(user);
        req.put("id",user.getId());
        return new Response(Response.SUCCESS, "注册成功！", req);
    };
    @PostMapping
    public Response registry (@RequestBody UserRequest user) {

        switch (service.registry(user)) {
            case 0:
                return new Response(Response.FAILURE, Response.Message.CODE_ERROR, null);
            case 1:
                return new Response(Response.SUCCESS, Response.Message.INSERT_OK, user);
            case -1:
                return new Response(Response.FAILURE, Response.Message.INSERT_ERROR, null);
        }
        return new Response(Response.FAILURE, Response.Message.INSERT_ERROR, null);
    }

    @PutMapping("forget")
    public Response forget (@RequestBody UserRequest user) {

        switch (service.forget(user)) {
            case 0:
                return new Response(Response.FAILURE, Response.Message.CODE_ERROR, null);
            case 1:
                return new Response(Response.SUCCESS, Response.Message.UPDATE_OK, user);
            case -1:
                return new Response(Response.FAILURE, Response.Message.UPDATE_ERROR, null);
        }
        return new Response(Response.FAILURE, Response.Message.UPDATE_ERROR, null);
    }

    @PutMapping("revise")
    public Response revise (@RequestBody UserRequest user) {
        return service.revise(user) == 1
                ? new Response(Response.SUCCESS, Response.Message.UPDATE_OK, user)
                : new Response(Response.FAILURE, Response.Message.UPDATE_ERROR, null);
    }

    @GetMapping("/code")
    public Response code (@RequestParam("email") String email, HttpSession session) throws MessagingException {
        if (CacheUtils.getWaiters().containsKey(session.getId())) {
            return new Response(Response.FAILURE, Response.Message.SEND_NOT_ALLOWED, null);
        }
        if (service.code(email, session.getId())) {
            return new Response(Response.SUCCESS, Response.Message.SEND_OK, null);
        } else
            return new Response(Response.FAILURE, Response.Message.SEND_ERROR, null);
    }

    @GetMapping("/info")
    public Response one(){
        return new Response(Response.SUCCESS, infoService.one());
    }

    @GetMapping("/plate/{page}/{size}")
    public Response list(@PathVariable("page") Integer page, @PathVariable("size") Integer size, String query, String section) {

        return new Response(Response.SUCCESS, plateService.query(page, size, query, section));
    }
    @GetMapping("/plateDetail")
    public Response getDetail(int id) {
        return new Response(Response.SUCCESS, plateService.one(id));
    }

    @GetMapping("/section")
    public Response list(Integer type) {

        return new Response(Response.SUCCESS, sectionService.list(type));
    }
}
